package travlefate.story.fragment;

import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;

import travlefate.story.R;
import travlefate.story.adapter.StoryListAdapter;
import travlefate.story.base.BaseFragment;
import travlefate.story.bean.ResultBase;
import travlefate.story.bean.ResultStory;
import travlefate.story.utils.Http;
import travlefate.story.utils.Loger;
import travlefate.story.views.PullToRefreshRecycleView;

/**
 * @author keven
 * @data 15/12/21 下午3:01
 * @package travlefate.story.fragment
 */

public class FramgentStroy extends BaseFragment {
    private static final String TAG = "FramgentStroy";
    String mType;
    private PullToRefreshRecycleView mRecycleView;
    private StoryListAdapter mAdapter;
    private Handler handler = new Handler();

    public FramgentStroy() {
        super();
        this.mType = "new";
    }

    @Override
    protected void initDatas() {

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());

        mRecycleView.setLayoutManager(layoutManager);

        mAdapter = new StoryListAdapter(getActivity());

        mRecycleView.setAdapter(mAdapter);

    }

    @Override
    protected void initClick() {
        //滑动到底部 加载更多
        mRecycleView.setOnlastVisibleListener(new PullToRefreshRecycleView.LastVisibleListener() {
            @Override
            public void onLastVisibleListener() {
                if (!isLoad) {
                    isLoad = true;
                    loadData(true);
                }

            }
        });

        //下啦刷新 清空重新加载
        mRecycleView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<RecyclerView>() {
            @Override
            public void onRefresh(PullToRefreshBase<RecyclerView> refreshView) {
                if (!isLoad) {
                    isLoad = true;
                    loadData(false);
                }

            }
        });

        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mRecycleView.setRefreshing();
            }
        }, 500);
    }

    @Override
    protected void initViews(View view) {
        mRecycleView = (PullToRefreshRecycleView) view.findViewById(R.id.story_list);
    }

    @Override
    protected View initLayout(ViewGroup container) {
        return LayoutInflater.from(container.getContext()).inflate(R.layout.fragment_story_list, null);
    }


    private static final int START_PAGE = 1;
    private int page = START_PAGE;
    private boolean isLoad = false;

    /**
     * @param isMore 是否味加载更多
     */
    private void loadData(final boolean isMore) {

        if (!isMore) {
            page = START_PAGE;
        }

        //创建OKHTTP
        OkHttpClient client = Http.getInstanse();

        //创建请求提交信息
        RequestBody body = new FormEncodingBuilder()
                .add("type", mType)
                .add("page", String.valueOf(page))
                .build();
        //创建请求
        Request.Builder builder = new Request.Builder();
        builder.url(Http.getStorys);
        builder.post(body);
        Request build = builder.build();
        //执行请求
        client.newCall(build).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                isLoad = false;
                if (mRecycleView.isRefreshing()) {
                    mRecycleView.onRefreshComplete();
                }
                Loger.i(TAG, "访问出错");
            }

            @Override
            public void onResponse(Response response) throws IOException {
                isLoad = false;
                String result = response.body().string();
                if (result != null) {
                    Loger.i(TAG, result);
                    Gson gson = new Gson();
                    Type type = new TypeToken<ResultBase<ArrayList<ResultStory>>>() {
                    }.getType();
                    final ResultBase<ArrayList<ResultStory>> resultList = gson.fromJson(result, type);

                    if (resultList.getResult().equals("0")) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (getActivity() != null) {
                                    Toast.makeText(getActivity(), "没有更多数据", Toast.LENGTH_SHORT).show();
                                }
                                if (mRecycleView.isRefreshing()) {
                                    mRecycleView.onRefreshComplete();
                                }
                            }
                        });
                    } else if (resultList != null && resultList.getData() != null && !resultList.getData().isEmpty()) {
                        Loger.i(TAG, "size:" + resultList.getData().size());
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (!isMore) {
                                    mAdapter.clearDatas();
                                }
                                mAdapter.addDatas(resultList.getData());
                                if (mRecycleView.isRefreshing()) {
                                    mRecycleView.onRefreshComplete();
                                }
                                page++;
                            }
                        });
                    }
                }
            }
        });
    }
}
